package edu.arizona.arid.akshen.view;
import java.io.IOException;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class ImageView extends Canvas {
	private Image image;

	public ImageView() {
		
	}
	
	public ImageView(String filePath) throws IOException {
		image = Image.createImage(filePath);
		System.out.println("ImageView.ImageView("+filePath+"), image="+image+"\n");
	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	protected void paint(Graphics g) {
		System.out.println("ImageView.paint()");
		g.drawImage(resizeImage(image, 200, 140), 0, 0, Graphics.TOP | Graphics.LEFT);
		
	}
	
	/**
	 * Resizes a given image
	 * 
	 * @param image
	 * @param width
	 * @param height
	 * @return
	 */
	public static Image resizeImage(Image image, int width, int height) {
		int srcWidth = image.getWidth();
		int srcHeight = image.getHeight();

		Image newImage = Image.createImage(width, height);
		Graphics g = newImage.getGraphics();

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				g.setClip(x, y, 1, 1);
				int dx = x * srcWidth / width;
				int dy = y * srcHeight / height;
				g.drawImage(image, x - dx, y - dy, Graphics.LEFT | Graphics.TOP);
			}
		}

		return Image.createImage(newImage);
	}

}
